package com.file.parser;

import com.file.bo.AppAlipayCr;
import com.file.bo.AppAlipayIdCard;
import com.file.bo.AppAlipayPersonal;
import com.file.bo.ResponseData;
import com.file.constant.ErrorCode;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 支付宝-芝麻分xml解析
 */

@Slf4j
public class AppAlipayCrXmlParser extends AppAlipayBaseXmlParser{

    public ResponseData<String> parseAppAlipayCrXmlToJson(String daId, String filePath, List<String> zhimafenNoDataScenarioList) {
        log.info("parseAppAlipayCrXmlToJson started, daId:{}, filePath:{}", daId, filePath);
        String json;

        try {
            if (filePath.contains("alipay_cr")) {
                AppAlipayCr appAlipayCR = parseAppAlipayCrXml(daId, filePath, zhimafenNoDataScenarioList);
                json = JsonUtils.convertObjectToJson(appAlipayCR);
            } else if (filePath.contains("alipay_personal")) {
                AppAlipayPersonal appAlipayPersonal = parseAppAlipayPersonalXml(filePath);
                json = JsonUtils.convertObjectToJson(appAlipayPersonal);
            } else if (filePath.contains("alipay_idcard")) {
                AppAlipayIdCard appAlipayIdCard = parseAppAlipayIdcardXml(filePath);
                json = JsonUtils.convertObjectToJson(appAlipayIdCard);
            } else {
                throw new RuntimeException("the file name is not supported");
            }
        } catch (Exception e) {
            log.error("|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseAppAlipayCrXmlToJson failed", e);
            return new ResponseData<>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(),
                    ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseAppAlipayCrXmlToJson completed, daId:{}, filePath:{}", daId, filePath);
        return new ResponseData<>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    private AppAlipayCr parseAppAlipayCrXml(String daId, String filePath, List<String> zhimafenNoDataScenarioList) throws DocumentException {
        AppAlipayCr appAlipayCR = null;

        List<String> nodeTextList = getNodeTextList(filePath);
        String zhimafenNoDataKeyword = getNoDataKeyWord(nodeTextList, zhimafenNoDataScenarioList);

        //有数据的正常页面，走正常设值逻辑
        if (isNormalCase(nodeTextList)) {
            appAlipayCR = processNormalCase(nodeTextList);
        //命中无数据关键字配置，走无数据设值逻辑
        } else if (StringUtils.isNotBlank(zhimafenNoDataKeyword)) {
            appAlipayCR = processNoDataCase(zhimafenNoDataKeyword);
        //一些非正常页面，将已知case逐个在这里适配
        } else {
            throw new RuntimeException("Zhimafen xml meet new case");
        }

        return appAlipayCR;
    }

    private AppAlipayCr processNoDataCase(String zhimafenNoDataKeyword) {
        AppAlipayCr appAlipayCR = new AppAlipayCr();
        appAlipayCR.setCaseDesc(zhimafenNoDataKeyword);
        return appAlipayCR;
    }

    private AppAlipayCr processNormalCase(List<String> nodeTextList) {
        AppAlipayCr appAlipayCR = new AppAlipayCr();
        int zhimaScoreIndex = 0;
        for (int i = 0; i < nodeTextList.size(); i++) {
            if (nodeTextList.get(i).contains("芝麻分")) {
                zhimaScoreIndex = i;
                break;
            }
        }

        for (int i = zhimaScoreIndex + 1; i < nodeTextList.size(); i++) {
            String nodeText = nodeTextList.get(i).trim();
            // 正常情况下，芝麻分取值范围是350-950
            if (nodeText.matches("[3-9]\\d{2}") && StringUtils.isBlank(appAlipayCR.getZhimaScore()) && isValidZhimafenScore(nodeText)) {
                appAlipayCR.setZhimaScore(nodeText);
                continue;
            }

            Pattern pattern = Pattern.compile("\\d{4}年\\d{2}月\\d{2}日");
            Matcher matcher = pattern.matcher(nodeText);
            // 上次更新2022年10月08日
            if (matcher.find()) {
                appAlipayCR.setLastUpdate(matcher.group());
            }
        }

        if (StringUtils.isAnyBlank(appAlipayCR.getZhimaScore())) {
            throw new RuntimeException("the parsed field zhimaScore has empty value");
        }
        return appAlipayCR;
    }

    private boolean isValidZhimafenScore(String zhimaScore) {
        int score = Integer.parseInt(zhimaScore);
        return 350 <= score && score <= 950;
    }

    private boolean isNormalCase(List<String> nodeTextList) {
        boolean hasZhimaScore = false;

        for (String nodeText : nodeTextList) {
            if (nodeText.contains("芝麻分")) {
                hasZhimaScore = true;
            }
        }
        return hasZhimaScore;
    }

    public static void main(String[] args) {
        AppAlipayCrXmlParser appAlipayCRXmlParser = new AppAlipayCrXmlParser();
        List<String> zhimafenNoDataScenarioList = Arrays.asList("暂时无法开通");;
        String json = appAlipayCRXmlParser.parseAppAlipayCrXmlToJson("", "C:\\Users\\lingfeng\\Downloads\\zd2qrnk81791399044102787072_3d05ad835c42fed09c05295b4e7a5adf_alipay_cr.xml", zhimafenNoDataScenarioList).getData();
        System.out.println(json);


    }
}
